from tree_sitter import Language, Parser, Tree, Node
import tree_sitter_cpp
import os, json
from .file_analyze import FileAnalyze

class ProjectAnalyze:
    def __init__(self, project_path):
        self.project_path = project_path
        self.file_path = None
        self.language = Language(tree_sitter_cpp.language())
        self.defined_types: dict = {}
        with open("/disk0/wyf/Project/zz_static_project/type_definitions.json", "r") as file:
            self.defined_types = json.load(file)

        self.test_result = {"True": [], "False": []}

    def get_all_files(self) -> list[str]:
        all_files = []
        for root, _, files in os.walk(self.project_path):
            for file in files:
                all_files.append(os.path.join(root, file))
        return all_files
    
    def global_analyze(self) -> None:
        all_files = self.get_all_files()
        for file in all_files:
            if file.endswith('.c') or file.endswith('.h'):
                self.file_path = file
                with open(self.file_path, 'rb') as f:
                    file_content = f.read()
                try:
                    file_analyze = FileAnalyze(file_content, self.defined_types)
                except Exception as e:
                    if not os.path.exists("/disk0/wyf/Project/zz_static_project/exceptions.txt"):
                        open("/disk0/wyf/Project/zz_static_project/exceptions.txt", "w").close()
                    with open("/disk0/wyf/Project/zz_static_project/exceptions.txt", "a") as log_file:
                        log_file.write(f"Error analyzing file {self.file_path}: {e}\n")
                    continue
                for key, value in file_analyze.function_definitions.items():
                    if value["transferability"] == True:
                        self.test_result["True"].append({"function_name": key, \
                                                         "file_path": self.file_path})
                    else:
                        self.test_result["False"].append({"function_name": key, \
                                                          "file_path": self.file_path})
                        if "transferability_detail" in value.keys():
                            self.test_result["False"][-1]["detail"] = value["transferability_detail"]
        
    def save_test_result(self) -> None:
        json.dump(self.test_result, open(f"{self.project_path}_test_result.json", "w"), indent=4)   